package 我的Java学习_算法基础.day_03;

import java.util.Random;

import static 我的Java学习_算法基础.day_01.唯一成对的数.printArray;

public class _037_分治模式的完美诠释_归并排序 {

    public static void main(String[] args) {
        int[] array = new int[5];
        Random random = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(20);
        }
        printArray(array);
        mergeSort(array, 0, array.length - 1);
        printArray(array);
    }

    public static void mergeSort(int[] array, int begin, int end) {
        if (begin < end) {
            int mid = begin + ((end - begin) >> 1);
            mergeSort(array, begin, mid);
            mergeSort(array, mid + 1, end);
            merge(array, begin, mid, end);
        }
    }

    static void merge(int[] array, int begin, int mid, int end) {
        int[] helper = new int[array.length];
        for(int i =begin;i<=end;i++){
            helper[i]=array[i];
        }
        int left = begin, right = mid + 1;
        int current = begin;
        while ((left <= mid) && (right <= end)) {
            if (helper[left] <= helper[right]) {
                array[current] = helper[left];
                current++;
                left++;
            } else {
                array[current] = helper[right];
                current++;
                right++;
            }
        }
        while (left <= mid) {
            array[current] = helper[left];
            current++;
            left++;
        }

    }
}
